
package org.vt.eldercare.serial;



import java.util.ArrayList;
import java.util.List;


public class USBPortRunnable implements Runnable {

	private TwoWaySerialComm usbComm;

	private final USBPortListener listener;
	private static boolean response = false;
	String connected="";


	public USBPortRunnable(TwoWaySerialComm usbComm, USBPortListener listener) {
		this.usbComm = usbComm;
		this.listener = listener;
	}

	public void run() {
		while (true) {
			
			List<String> myList = new ArrayList<String>();
			myList = TwoWaySerialComm.listPorts();
			if (myList.isEmpty()) {
				if (usbComm.isConnected()) {
					System.err.println("Error: No Ports Connected");
					setResponse(false);
					usbComm.close();
					portUnplugged();
				}
			} else {
				if (!usbComm.isConnected()) {

					for (String s : myList) {
						try {

							usbComm.connect(s);


							usbComm.serialWrite(0, SerialWriter.SEND_ECHO);
							Thread.sleep(2000);
					

							if (!response) {
								// if no response disconnect
								usbComm.close();
								System.out.println("Response is " + response);
							} else {
								connected=s;
								portConnected(s);
								System.out.println("Response is " + response);
								break;
							}

						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				if(usbComm.isConnected()) {
					if(TwoWaySerialComm.checkUnplugged(myList, connected)) {
						setResponse(false);
						usbComm.close();
						portUnplugged();
						System.out.println("Port disconnected");
						
					}
				}
			}
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	// Synchronized
	public synchronized static void setResponse(boolean r) {

		response = r;
	}
	public static boolean getResponse() {
		
		return response;
	}

	private void portConnected(final String portName) {
		(new Thread(new Runnable() {
			public void run() {
				listener.onPortConnected(portName);
			}
		})).start();
	}

	private void portUnplugged() {
		(new Thread(new Runnable() {
			public void run() {
				listener.onPortUnplugged();
			}
		})).start();
	}

}
